package com.ubox.mqtt_upush.controller;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.ubox.mqtt_upush.domain.PushMsg;
import com.ubox.mqtt_upush.http.ResponseMsg;
import com.ubox.mqtt_upush.mqttbroker.SessionFilter;
import com.ubox.mqtt_upush.mqttclient.FuseMQTTClientProvider;
import com.ubox.mqtt_upush.utils.JsonUtil;
 
@RestController
public class MqttPushController {
	
	private final static Logger logger = LoggerFactory.getLogger(MqttPushController.class);
	 
	@Resource
	protected FuseMQTTClientProvider client;
	
	@Resource
	SessionFilter sessionFilter;
	
	/**
	 * 向设备发送消息
	 * @param app
	 * @param innerCode
	 * @param topic
	 * @param pushMsg
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/upush", method = RequestMethod.POST, produces = "application/json;charset=UTF-8", consumes = "application/json;charset-UTF-8")
	public ResponseMsg sendMsg(@RequestBody PushMsg pushMsg) throws Exception {
		if(client==null||!client.isConnected())
		{
			client.connect();
		}
		try {
			client.publish(pushMsg.getTopic(), JsonUtil.toString(pushMsg.getMsg()).getBytes(),pushMsg.getQos());
			//logger.info("[{}] publish mqtt msg to topic: {} msg: {} qos: {}",client.getUsername(),msg.getTopic(),msg,msg.getQos());
		} catch (Exception e) {
			logger.error("sendMsg msg error : {}",JsonUtil.toString(pushMsg),e);
		}

		return new ResponseMsg();
	}
	
	/**
	 * 查询设备在线状态
	 * @param app
	 * @param innerCode
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/isOnline/{app}/{innerCode}", method = RequestMethod.GET)
	public boolean isOnline(@PathVariable("app")String app,@PathVariable("innerCode")String innerCode) throws Exception {

		return sessionFilter.isOnline(app,innerCode);
	}

}
